<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9 0009
 * Time: 15:51
 */

namespace app\api\controller;
use app\api\model\User;
use lib\RedisDB;
use lib\wechat\WxSmallClient;
use think\Controller;
use think\Db;
use think\Request;
class UserController extends Controller
{
    private $user_info;
    private $openid;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $img = request()->file('img');
        if(!$img){
            $this->openid = $this->request->param('openid');
            if(!$this->openid){
                respon(210,'参数错误');
            }
            $this->user_info = json_decode($this->redis->get($this->openid));
            if(!$this->user_info){
                respon(210,'用户信息错误！');
            }
        }

    }
    /*
     * 用户中心资料展示
     *
     * **/
    public function index(){
        /*首页
         * */
        $data=array();
        $user_id=$this->user_info->id;
        $where['openid'] = $this->openid;
        $result=Db::name('user_extend')->where($where)->field('nickname,avatar_url,u_sign')->find();
        if(!$result){
            return respon(270,'系统繁忙，请稍后再试');
        }
        $fwhere='user_id = '.$user_id;
        $data['nickname']=$result['nickname'];
        $data['avatar_url']=$result['avatar_url'];
        $data['u_sign']=$result['u_sign']?$result['u_sign']:'暂无签名';
        $collections=Db::name('collections')->where($fwhere)->where(['is_valid'=>1])->count(1);
        $forwarding=Db::name('forwarding')->where($fwhere)->group('content_id')->count(1);
        $token= Db::name('user_token')->where('user_id = '.$user_id)->sum('token');
        $data['sum_forward']=$forwarding?$forwarding:0;//转发次数
        $data['token']=$token?$token:0;
        $data['collections']=$collections?$collections:0;
        $data['sum_item']=5;//项目还未完工，暂时按固定值
        return respon(200,$data);
    }

    /**
     *更新用户的formid
     */
    public function addFormId(){
        $openid=input('post.openid');
        $formId=input('post.formId');
        if(!$openid || !$formId){
            return respon(0,'参数错误！');
        }
        $res = User::get(['openid'=>$openid]);
        if($res){
            User::update(['form_id'=>$formId],['openid'=>$openid]);
        }
    }
    /*
         *用户点击头像互看身份信息
         *
         * **/
    public function get_other(){
        $data=array();
        $page = input('post.page');
        $arr=wechat_page($page,'10');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $openid=input('post.openid');
        $other_id=input('post.user_id');
        if(!input('post.openid')||!input('post.user_id')){
            return respon(230,'openid未获取到');
        }
        $user_id=$this->user_info->id;
        $where='id = '.$other_id;
        $swhere='id = '.$user_id;
        $re=Db::name('user')->where($where)->field('phone,is_figure')->find();
        $row=Db::name('user')->where($swhere)->field('is_figure')->find();
        if($re['is_figure']==1 && $row['is_figure']!=1){
            return respon(291,'对不起，你没有访问权限！');
        }
        $result = Db::name('user_extend')
            ->where('phone = '.$re['phone'])
            ->field('nickname,gender,province,avatar_url,u_sign,u_age,u_like,work')
            ->find();
        $fwhere='user_id = '.$other_id;
        $data['nickname']=$result['nickname'];
        if($result['gender']==1){
            $data['gender']='男';
        }elseif($result['gender']==2){
            $data['gender']='女';
        }else{
            $data['gender']='保密';
        }
        $data['avatar_url']=$result['avatar_url'];
        $data['work']=$result['work'];
        $data['province']=$result['province']?$result['province']:'';
        $data['u_sign']=$result['u_sign']?$result['u_sign']:'';
        $data['u_like']=$result['u_like']?$result['u_like']:'';
        $data['u_age']=$result['u_age']?$result['u_age']:'';
        $rse=Db::name('film_review')->where($fwhere)->count(0);
        if($re['is_figure']==1){
            $wh='other_id = '.$other_id;
            $figure_re=Db::name('figure_review')
                ->where($wh)
                ->field('user_id,content,pag,create_at')
                ->limit($offset,$length)
                ->select();
            if($figure_re){
                foreach ($figure_re as $k=>$v){
                    $where='u.id = '.$v['user_id'];
                    $op=Db::name('user')
                        ->alias('u')
                        ->join('user_extend ue','u.phone = ue.phone','left')
                        ->join('figure_review fi','u.id = fi.user_id','left')
                        ->where($where)
//                        ->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')
                        ->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url,fi.content,fi.pag,fi.create_at')
                        ->find();
//                    $figure_re = array_merge($op[0],$v);
                    $data['other'][] = $op;
                }
//                $data['other'] =$figure_re;
//                $data['other'] = (!empty($figure_re)) ? $figure_re : array('status'=>260);
            }
        }else{
            $forward_con=Db::name('film_review')
                ->where($fwhere)
                ->field('movie_id,title,rate,type,s_review,l_review,like_count,comment_count,created_at')
                ->limit($offset,$length)
                ->select();
            $data['data']=$forward_con;
        }
        $forwarding=Db::name('forwarding')->where($fwhere)->count(0);
        $collections=Db::name('collections')->where($fwhere)->where(['is_valid'=>1])->count(1);
        $data['sum_review']=$rse?$rse:0;//评论次数
        $data['sum_forward']=$forwarding?$forwarding:0;//转发次数
        $data['sum_collections']=$collections?$collections:0;//转发次数
        $data['sum_item']=0;//项目还未完工，暂时按固定值
        $data['is_figure']=$re['is_figure'];//否是是影人认证凭证
        $data['data']=$forward_con;
        return respon(200,$data);
    }







    public function test(){
        session('ccc',123);
//        $arr=$_POST['phone'];
//        $result = model('login')->getMsgCode($arr,"您的验证码是：【__CON__】。请不要把验证码泄露给其他人。如非本人操作，可不用理会！");
    }

    /*
     * Ajax上传保存图片,并返回图片路径
     *
     * **/
    public function Ajax_upload(){
        $data=array();
        $hand_card=request()->file('hand_card');
        $company_image=request()->file('company_image');
        $company=Upload($company_image,1);
        $hand=Upload($hand_card,1);
        if(is_array($hand)){
            return json_encode($hand);
        }
        if(is_array($company)){
            return json_encode($company);
        }
        $data['status']=200;
        $data['hand_card']=$hand;
        $data['company_image']=$company;
        return json_encode($data);
    }

    /*
     * Ajax上传保存图片公共方法,并返回图片路径
     *
     * **/
    public function Ajax_img(){
        $img = request()->file('img');
        if($img){
            $info=$img->move('upload/ticket');
            if(!is_array($info)){
                $data['img_url']='upload/ticket/'.$info->getSaveName();
                respon(200,$data);
            }else{
                respon(201,'上传失败!'.$info[0]);
            }
        }
        respon(270,"上传失败!");
    }

    /*
     * 影人身份认证
     *
     *
     * **/
    public function shadman_rz(){
        $data=array();
        $data['user_id'] = $this->user_info->id;
        $res = Db::name('user')->where(['id'=>$this->user_info->id])->field('is_figure')->find();
        if($res['is_figure'] == 1){
            return respon(200,"已通过审核！");
        }
        $re=Db::name('figure')->where('user_id = '.$data['user_id'])->field('id')->find();
        if($re){
            return respon(215,"您已提交成功，请等待审核！");
        }
        if(!input('post.fig_name')){
            return respon(210,"请输入真实姓名！");
        }
        if(!input('post.fig_job')){
            return respon(210,"请输入职务信息！");
        }
        if(!input('post.fig_phone')){
            return respon(210,"请输入手机信息！");
        }
        if(!input('post.fig_company')){
            return respon(210,"请输入所属公司！");
        }
        if(!input('post.fig_achievement')){
            return respon(210,"请输入主要成就！");
        }
        if(!input('post.fig_introduction')){
            return respon(210,"请输入信息简介！");
        }
        /*if(!input('post.hand_card') || !input('post.company_image')){
            return respon(210,"需要上传图片信息！");
        }*/

        $data['fig_name']=input('post.fig_name');
        $data['fig_phone']=input('post.fig_phone');
        $data['fig_job']=input('post.fig_job');
        $data['fig_company']=input('post.fig_company');
        $data['fig_achievement']=input('post.fig_achievement');
        $data['fig_introduction']=input('post.fig_introduction');
        $data['hand_card']=input('post.hand_card')?input('post.hand_card'):'';
        $data['company_image']=input('post.company_image')?input('post.company_image'):'';
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $result=Db::name('figure')->insert($data);
        if($result > 0){
            return respon(200,"提交成功！");
        }
        return respon(250,"提交失败，请稍后再试！");
    }

    /**发送验证码和绑定手机都是统一接口
     * 绑定手机号
     */
    public function bindPhone(){
        if(Request::instance()->post()){
            $openid=$this->openid;
            $phone=input('post.phone')?input('post.phone'):false;
            $msg=input('post.msg_code')?input('post.msg_code'):false;
            if($msg && $phone && $openid){
                $data=$this->getMsgCode($phone);
                if($data){
                    if($msg == $data){
                       $re=model('User')->bn_phone($openid,$phone);
                       if($re){
                           $us=json_decode($this->redis->get($openid),true);
                           $us['phone']=$phone;
                           $us['id']=$re;
                           $this->redis->del($this->openid);
                           $this->redis->setnx($openid,json_encode($us));
                           respon(200,"绑定成功！");
                       }else{
                           respon(210,"未知错误，请稍后再试");
                       }
                    }else{
                        return respon(211,"验证码错误,请您重新输入！");
                    }
                }else{
                    return respon(209,"您的验证码已失效,请您重新获取验证码！");
                }
            }else{
                if(!WSTIsPhone($phone)){
                    respon(213,"手机号格式不正确!");
                }
                if(!$openid){
                    respon(230,'openid未获取到');
                }
                $User = model('User');
                $result=$User->phoneVer($phone,$openid);
                if($result){
                    return json($result);
                }else{

                    $res=$this->sendCode($phone,"您的验证码是：【__CON__】。请不要把验证码泄露给其他人。如非本人操作，可不用理会！");
                }
                return json($res);
            }

        }
    }



    /**
     * @desc  获取短信验证码
     * @param $phone
     * $extime=300秒 session有效时间设置为300秒
     *
     */
    public function getMsgCode($phone){
        if(empty($phone)) return false;
        $dbo = Db::name('phone_msg')->where(['phone'=>$phone])->field('exp_time,phone_msg')->find();
        $newtime=time();
        if($newtime > $dbo['exp_time']){
           return false;
        }
        return $dbo['phone_msg'];

    }

    /**
     * 手机登陆
     */
    public function mobile_index(){
        $mmr_phone = I('mmr_phone');
        $mmr_password = I('mmr_password',0,'md5');
        $result = D('User')->mobileLogin($mmr_phone,$mmr_password);

        $this->ajax_Return($result['data'],$result['info'],$result['status']);
    }

    /**获取转发的文章
     * 点击转发展示转发的文章标题
     */
    public function getForword(){
        $user_id = $this->user_info->id;
        $type=input('post.type');
        $page=input('post.page')?input('post.page'):0;
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        if(!in_array($type,[1,2])){
            respon(230,'类型错误');
        }
        $where['user_id'] = $user_id;
        $where['type'] = $type;
        $result = Db::name('forwarding')->where($where)->field('type,forward_target,content_id,title')->limit($offset,$length)->select();
        if(!$result){
            respon(270,"未查询到数据！");
        }
        foreach ($result as &$v){
            //类型1 电影 类型2 长评
            if($type==1){
                $movie = Db::name('movies')->where('id',$v['content_id'])->field('id,name,directed,rate,movie_image,stars,initial_release_date,douban_id')->find();
                $v['movie'] = $movie?$movie:null;
            }elseif ($type==2){
                $review = Db::name('film_review')->where(['id'=>$v['content_id'],'status'=>1])->find();
                if($review){
                    $user_info=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where(['u.id'=>$review['user_id']])->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->find();
                    $review['user_info'] = $user_info?$user_info:null;
                }
                $v['review'] = $review?$review:null;
            }
        }
        respon(200,$result);
    }


    /**获取评论的文章
     * 点击评论展示我的评论
     * openid 用户
     * movie_id 电影id
     * page 页数
     */
    public function getFilmReview(){
        $data=input('post.');
        if($data['user_id']){
            $user_id=session($data['user_id']);
        }elseif($data['openid']){
            $user_id=session($data['openid']);
        }
        if(!$user_id){
            respon(230,'openid未获取到');
        }
        $movie_id=input('post.movie_id');
        $page = input('post.page');
        $type=input('post.type')?input('post.type'):0;//提交过来的评论类型，默认为0查询全部，1短评，2长平
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        if(!$user_id && !$movie_id){
            return respon(230,'openid未获取到');
        }
        $result=movies_review($user_id,$movie_id,$type,$offset,$length);
        if($result){
            return respon(200,$result);
        }else{
            return respon(270,"未查询到数据！");
        }

    }


    /**获取用户的所有资料
     *
     */
    public function getUserInfo(){
        $user_id = $this->user_info->id;
        $openid=$this->openid;
        $where='openid = '."'{$openid}'";
        $swhere='id = '.$user_id;
        $data=Db::name('user')->where($swhere)->field('is_figure')->find();

        $result = Db::name('user_extend')->where($where)->field('nickname,gender,province,avatar_url,u_sign,u_age,u_like,work,wallet')->find();

        $result['is_figure']=$data['is_figure']?$data['is_figure']:0;
        $result['first_job']="";
        if($result['is_figure']==1){
            $re=Db::name('figure')->where('user_id = '.$user_id)->field('fig_job')->find();
            $result['first_job']=$re['fig_job'];
        }
        if($result){
            return respon(200,$result);
        }else{
            return respon(270,"未查询到数据！");
        }

    }

    /**ajax更改用户信息
     *
     */
    public function ajax_change_info(){
        $openid=input('post.openid');
        if(!$openid){
            return respon(230,'openid未获取到');
        }
        $data=input('post.');
        unset($data['openid']);//取出openid
        if( empty($data) || !is_array($data) )
        {
            return respon(210,"参数不全！");
        }
        foreach ($data as $key=>$value){
            if(empty($key))
            {
                continue;
            }
            $result[]=Db::name('user_extend')->where('openid = '."'{$openid}'")->update($data);
        }
        return respon(200,"更新成功！");

    }


    /*
     * 获取token记录，就是跳转到我的钱包
     * **/
    public function getToken(){
        $openid=input('post.openid');
        $user_id=session($openid);
        $page = input('post.page');
        if(!$user_id){
            return respon(230,'openid未获取到');
        }
        $arr=wechat_page($page,'10');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where='to_user_id = '.$user_id;
        $result = Db::name('token')->where($where)->field('to_type,token,created_at')->limit($offset,$length)->select();
        $re= token_arr($result);
        if($re){
            return respon(200,$re);
        }else{
            return respon(270,"未查询到数据！");
        }
    }

    /*
     * 获取我的足迹
     * **/
    public function getFoot(){
        $user_id=$this->user_info->id;
        $page = input('post.page');
        $arr=wechat_page($page,'10');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where='fp_user_id = '.$user_id;
        $result = Db::name('footprint')->where($where)->field('fp_type,fp_conid,created_at')->group('fp_conid')->limit($offset,$length)->select();

        foreach ($result as $key=>$value){
            if($value['fp_type']==1){
                $result[$key]['movie']=Db::name('movies')->where('id ='.$value['fp_conid'])->field('id,name,directed,rate,movie_image,stars,initial_release_date,douban_id')->find();
            }elseif ($value['fp_type']==2){
                //$result[$key]['movie']=Db::name('movies')->where('id ='.$value['fp_conid'])->field('id,name,type,duration,movie_image')->find();
            }
        }
        if($result){
            return respon(200,$result);
        }else{
            return respon(270,"未查询到数据！");
        }
    }

    /*
     * 获取我的收藏，收藏的电影
     * **/
    public function getCollect(){
        $user_id=$this->user_info->id;
        $page = input('post.page');
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where = [
            'user_id'=>$user_id,
            'is_valid'=>1
        ];
        $result = Db::name('collections')->where($where)->field('type,movie_id,item_id')->select();
        $re= collect_arr($result);
        $data=array();
        if($re['movie_id']){
            $data['movie']=Db::name('movies')->where('id in ('.$re['movie_id'].')')->field('id,name,directed,rate,movie_image,stars,initial_release_date,douban_id')->select();
        }
        /*if($re['item_id']){
            $data['item']=Db::name('film_review')->where('id in ('.$re['review_id'].')')->field('id,name,type,duration,movie_image')->select();
        }*/   //项目信息暂时封存
        if($data){
            respon(200,$data);
        }else{
            respon(270,"未查询到数据");
        }
    }

    /**
     * 添加收藏
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addCollect(){
        $id = input('post.id');
        $type = (int)input('post.type');//1.项目2.电影
        if(!$id || !$type){
            return respon(210,'参数错误！');
        }
        $user_id = $this->user_info->id;
        $where = [
            'type'=>$type,
            'user_id'=>$user_id
            ];
        if($type==1){
            $where['movie_id'] = $id;
        }else{
            $where['item_id'] = $id;
        }
        $result = Db::name('collections')
                //->alias('c')
                //->join('movies m', 'c.movie_id=m.id')
                ->where($where)->find();
        if($result){
            $is_valid = $result['is_valid']==1?0:1;
            $res = db('collections')->where(['id' =>$result['id']])->update(['is_valid'=>$is_valid]);
            if($res){
                return respon(200,'修改成功');
            }else{
                return respon(222,'修改失败');
            }
        }else{
            $where['created_at'] = date('Y-m-d H:i:s',time());
            $result=Db::name('collections')->insert($where);
            if($result){
                return respon(200,'添加收藏成功');
            }else{
                return respon(222,'添加收藏失败');
            }
        }
    }

    /*
     * 获取我的消息(系统推送，私信)
     * **/
    public function getNews(){

    }


    /*
     * 获取我参与的项目
     * **/
    public function getItem(){

    }

}